package com.breaktian.assemble.provider;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.widget.Toast;

import com.breaktian.assemble.utils.LogUtil;

import java.util.List;

/**
 * Created by tiankeke on 2017/5/25.
 * 地里位置提供者
 */

public class LocationProvider {

    private final Activity activity;

    private final int RELOAD = 0x21;
    private int RELOAD_TIME = 5000;
    public static long MIN_TIME = 5*1000;//5秒
    public static long MIN_DISTANCE = 1;//1米

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case RELOAD:
                    createProvider();
                    startLoadLocation();
                    break;
            }
        }
    };
    private LocationManager mLocationManager;
    private String mLocationProvider;
    private Location location;

    public LocationProvider(Activity activity) {
        this.activity = activity;
        createProvider();
    }

    private void createProvider() {
        //获取地理位置管理器
        mLocationManager = (LocationManager) activity.getSystemService(Context.LOCATION_SERVICE);
        //获取所有可用的位置提供器
        List<String> providers = mLocationManager.getProviders(true);
        if (providers == null) return;
        if (providers.contains(LocationManager.GPS_PROVIDER)) {
            //如果是GPS
            mLocationProvider = LocationManager.GPS_PROVIDER;
        } else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
            //如果是Network
            mLocationProvider = LocationManager.NETWORK_PROVIDER;
        }
    }

    /**
     * 开始load地理位置信息
     * 调用此方法需要获取位置权限，调用时请注意
     * */
    public void startLoadLocation() {
        LogUtil.d("startLoadLocation...");
        if (mLocationManager == null) {
            LogUtil.e("fail to get LocationManager instance");
            return;
        }
        if (TextUtils.isEmpty(mLocationProvider)) {
            //尝试打开wifi和gps
            LogUtil.d("try to open wifi and gps");
            Toast.makeText(activity,"为了定位准确，请尝试打开wifi和gps",Toast.LENGTH_SHORT).show();
            handler.sendEmptyMessageDelayed(RELOAD, RELOAD_TIME);
            return;
        }



        //如果没有赋予权限
        if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            LogUtil.e("LocationProvider can not startLoadLocation please granted location permission");
        }
        Location location = mLocationManager.getLastKnownLocation(mLocationProvider);
        if (location != null) {
            this.location = location;
        }

        mLocationManager.requestLocationUpdates(mLocationProvider, MIN_TIME, MIN_DISTANCE, locationListener);

    }

    /**
     * 获取位置对象
     * 获取到的坐标是gps硬件的坐标  也就是地球坐标
     * 但是如果要在中国的各个地图服务上显示需要转换成对应的坐标
     * 百度-百度坐标
     * 高德-火星坐标
     * ...
     * 资料: http://www.jianshu.com/p/0fe30fcd4ae7
     * */
    public Location getLocation(){
        return this.location;
    }

    /**
     * 停止
     * */
    public void stop(){
        LogUtil.d("stop...");
        handler.removeMessages(RELOAD_TIME);
        if (mLocationManager != null) {
            //移除监听器
            if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                    && ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            }
            mLocationManager.removeUpdates(locationListener);
        }
    }



    /**
     * LocationListern监听器
     * 参数：地理位置提供器、监听位置变化的时间间隔、位置变化的距离间隔、LocationListener监听器
     */
    LocationListener locationListener = new LocationListener() {

        @Override
        public void onStatusChanged(String provider, int status, Bundle arg2) {
            LogUtil.d("onStatusChanged...");
        }

        @Override
        public void onProviderEnabled(String provider) {
            LogUtil.d("onProviderEnabled...");
        }

        @Override
        public void onProviderDisabled(String provider) {
            LogUtil.d("onProviderDisabled...");
        }

        @Override
        public void onLocationChanged(Location location) {
            LogUtil.d("onLocationChanged... location Latitude:"+location.getLatitude()+",Longitude:"+location.getLongitude());
            //如果位置发生变化,重新显示
            if(location!=null){
                LocationProvider.this.location = location;
            }
        }
    };


}
